﻿using Newtonsoft.Json;
using SuperWebSocket;
using System;
using System.Windows.Interop;
namespace WpfLockScreen.Common
{
    public partial class SocketServer
    {
        public SocketServer()
        {
            websocketServer();
        }

        private void websocketServer()
        {
            WebSocketServer webSocketServer = new WebSocketServer();
            webSocketServer.NewSessionConnected += WebSocketServer_NewSessionConnected;
            webSocketServer.NewMessageReceived += WebSocketServer_NewMessageReceived;
            webSocketServer.SessionClosed += WebSocketServer_SessionClosed;

            if (!webSocketServer.Setup("127.0.0.1", 5000))
            {
                
            }

            if (!webSocketServer.Start())
            { 

            }
          
            //webSocketServer.Dispose();
        }

        private void WebSocketServer_NewSessionConnected(WebSocketSession session)
        {
            
            SendToAll(session, "11111");
        }

        private void WebSocketServer_NewMessageReceived(WebSocketSession session, string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                CardInfo info= JsonConvert.DeserializeObject<CardInfo>(value);
                if (info!=null)
                {
                    info.PatInfo = new PatInfo() { PatName="测试",PatNo="123"};
                    string res = JsonConvert.SerializeObject(info);
                    SendToAll(session, res);
                }
            }
        }

        private void WebSocketServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
          
        }

        /// 广播，同步推送消息给所有的客户端

        public static void SendToAll(WebSocketSession webSocketSession, string msg)
        {
            foreach (var item in webSocketSession.AppServer.GetAllSessions())
            {
                item.Send(msg);
            }
        }


    }

}